package cn.nvrelax.cloudnote.syskit;

import cn.nvrelax.cloudnote.entity.User;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 程序描述：验证token合法性，并将用户基础参数加入request属性“authUser”中
 * 加入的基础参数有：id nickName sex type
 * token不合法将会直接拦截请求并返回错误信息
 * 创建时间：2019/6/4 19:19
 * 编码：nvRelax
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Value("${cn.nvrelax.token.key}")
    private String encryptKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null) {
            return validFailure(response,"Token不存在",ResponseCode.NO_TOKEN_ERROR);
        }
        //验证Token合法性
        try {
            Claims claims = Jwts.parser().setSigningKey(encryptKey).requireIssuer("nvr")
                    .requireSubject("cloudnote").parseClaimsJws(token).getBody();
            //合法，从Token获取基础参数，加入请求属性中
            User user = new User();
            user.setId(claims.get("id",Integer.class));
            user.setSex(claims.get("sex",String.class));
            user.setNickname(claims.get("nickName",String.class));
            user.setType(claims.get("type",String.class));
            request.setAttribute("authUser",user);
            return true;
        } catch (JwtException e) {
            //不合法，返回错误信息
            return validFailure(response,"Token不合法",ResponseCode.TOKEN_VERIFY_ERROR);
        }
    }

    private boolean validFailure(HttpServletResponse response, String news, int code) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type","application/json");
        JSONObject object = new JSONObject();
        object.put("status", code);
        object.put("msg",news);
        response.getWriter().print(JSONObject.toJSONString(object));
        return false;
    }
}
